
/*   RolGPS Project
 * 
 *   Copyright (C) 2009 Pablo Alejandro Costesich <rhfixer@gmail.com>
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
package org.rolgps.libnstack.parser;

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import org.rolgps.libnstack.message.GenericMessage;
import org.rolgps.libnstack.protocol.Message;
import org.rolgps.libnstack.protocol.MessageParser;

/**
 *
 * @author xeph
 */
public class JSONParser implements MessageParser {

    Gson gson = new Gson();

    /**
     *
     * @param buffer
     * @return
     * @throws java.io.IOException
     */
    public Message parseString(BufferedReader buffer) throws IOException {
        Message result = null;
        if (buffer != null) {
            String line = buffer.readLine();
            StringBuffer jsonText = new StringBuffer();
            while (line != null && !line.equals(null)) {
                if(!line.equals("")){
                    jsonText.append(line);
                    if(line.startsWith("{") && line.endsWith("}")){
                        break;
                    }
                }
                line = buffer.readLine();
            }
            String toParse = jsonText.toString();
            System.err.println("<<<"+toParse);
            if(!toParse.equals("")){
                return gson.fromJson(toParse, GenericMessage.class);
            }

        }
        return result;
    }

    /**
     *
     * @param message
     * @return
     */
    public String parseMessage(Message message) {
        String result = "";
        result = gson.toJson(message);
        result.concat("\n\n");
        return result;
    }
}
